import { Router } from 'vue-router'
import { useMessage } from 'naive-ui'

// 路由跳转选项接口
interface NavigationOptions {
  replace?: boolean // 是否替换当前历史记录
  query?: Record<string, any> // 查询参数
  params?: Record<string, any> // 路由参数
  hash?: string // 锚点
  showMessage?: boolean // 是否显示跳转消息
  messageText?: string // 自定义消息文本
}

// 路由跳转工具类
export class RouterUtils {
  private router: Router
  private message: any

  constructor(router: Router) {
    this.router = router
    this.message = useMessage()
  }

  /**
   * 通过路由名称跳转
   * @param name 路由名称
   * @param options 跳转选项
   */
  async pushByName(name: string, options: NavigationOptions = {}) {
    const {
      replace = false,
      query = {},
      params = {},
      hash = '',
      showMessage = false,
      messageText = ''
    } = options

    try {
      console.log(`🚀 Navigating to route: ${name}`, { query, params, hash })
      
      // 检查路由是否存在
      const routes = this.router.getRoutes()
      const targetRoute = routes.find(r => r.name === name)
      
      if (!targetRoute) {
        const error = `路由 "${name}" 不存在`
        console.error('❌', error)
        this.message.error(error)
        return false
      }

      const routeConfig: any = { name }
      if (Object.keys(query).length > 0) routeConfig.query = query
      if (Object.keys(params).length > 0) routeConfig.params = params
      if (hash) routeConfig.hash = hash

      let result
      if (replace) {
        result = await this.router.replace(routeConfig)
      } else {
        result = await this.router.push(routeConfig)
      }

      if (showMessage) {
        const msg = messageText || `已跳转到${targetRoute.meta?.title || name}`
        this.message.success(msg)
      }

      console.log('✅ Navigation successful')
      return true
    } catch (error: any) {
      console.error('❌ Navigation failed:', error)
      this.message.error(`跳转失败: ${error.message || error}`)
      return false
    }
  }

  /**
   * 通过路径跳转
   * @param path 路径
   * @param options 跳转选项
   */
  async pushByPath(path: string, options: NavigationOptions = {}) {
    const {
      replace = false,
      query = {},
      showMessage = false,
      messageText = ''
    } = options

    try {
      console.log(`🚀 Navigating to path: ${path}`, { query })
      
      const routeConfig: any = { path }
      if (Object.keys(query).length > 0) routeConfig.query = query

      let result
      if (replace) {
        result = await this.router.replace(routeConfig)
      } else {
        result = await this.router.push(routeConfig)
      }

      if (showMessage) {
        const msg = messageText || `已跳转到 ${path}`
        this.message.success(msg)
      }

      console.log('✅ Navigation successful')
      return true
    } catch (error: any) {
      console.error('❌ Navigation failed:', error)
      this.message.error(`跳转失败: ${error.message || error}`)
      return false
    }
  }

  /**
   * 返回上一页
   * @param fallbackRoute 如果没有上一页时的备用路由
   */
  goBack(fallbackRoute: string = 'Dashboard') {
    try {
      if (window.history.length > 1) {
        this.router.go(-1)
        console.log('✅ Navigated back')
      } else {
        console.log('🔄 No history, navigating to fallback route')
        this.pushByName(fallbackRoute)
      }
    } catch (error: any) {
      console.error('❌ Go back failed:', error)
      this.pushByName(fallbackRoute)
    }
  }

  /**
   * 前进到下一页
   */
  goForward() {
    try {
      this.router.go(1)
      console.log('✅ Navigated forward')
    } catch (error: any) {
      console.error('❌ Go forward failed:', error)
      this.message.error('无法前进')
    }
  }

  /**
   * 重新加载当前页面
   */
  reload() {
    try {
      this.router.go(0)
      console.log('✅ Page reloaded')
    } catch (error: any) {
      console.error('❌ Reload failed:', error)
      window.location.reload()
    }
  }

  /**
   * 获取当前路由信息
   */
  getCurrentRoute() {
    return this.router.currentRoute.value
  }

  /**
   * 检查路由是否存在
   * @param name 路由名称
   */
  routeExists(name: string): boolean {
    const routes = this.router.getRoutes()
    return routes.some(r => r.name === name)
  }

  /**
   * 获取所有路由
   */
  getAllRoutes() {
    return this.router.getRoutes()
  }

  /**
   * 批量跳转（用于测试）
   * @param routes 路由名称数组
   * @param interval 间隔时间（毫秒）
   */
  async batchNavigate(routes: string[], interval: number = 1000) {
    for (const route of routes) {
      await this.pushByName(route, { showMessage: true })
      await new Promise(resolve => setTimeout(resolve, interval))
    }
  }
}

// 路由常量
export const ROUTE_NAMES = {
  LOGIN: 'Login',
  DASHBOARD: 'Dashboard',
  ORDER_MANAGEMENT: 'OrderManagement',
  PRODUCT_MANAGEMENT: 'ProductManagement',
  USER_MANAGEMENT: 'UserManagement',
  SYSTEM_MANAGEMENT: 'SystemManagement',
  PROFILE: 'Profile',
  IMAGE_MANAGEMENT: 'ImageManagement',
  NOT_FOUND: 'NotFound'
} as const

// 路由路径常量
export const ROUTE_PATHS = {
  LOGIN: '/login',
  DASHBOARD: '/',
  ORDER_MANAGEMENT: '/order-management',
  PRODUCT_MANAGEMENT: '/product-management',
  USER_MANAGEMENT: '/user-management',
  SYSTEM_MANAGEMENT: '/system-management',
  PROFILE: '/profile',
  IMAGE_MANAGEMENT: '/image-management'
} as const

// 快捷跳转函数
export const createRouterUtils = (router: Router) => {
  return new RouterUtils(router)
}

// 常用跳转方法的快捷函数
export const quickNavigation = {
  toDashboard: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.DASHBOARD),
  toLogin: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.LOGIN),
  toProfile: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.PROFILE),
  toOrderManagement: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.ORDER_MANAGEMENT),
  toProductManagement: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.PRODUCT_MANAGEMENT),
  toUserManagement: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.USER_MANAGEMENT),
  toSystemManagement: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.SYSTEM_MANAGEMENT),
  toImageManagement: (router: Router) => createRouterUtils(router).pushByName(ROUTE_NAMES.IMAGE_MANAGEMENT)
} 